package org.example.project.service.impl;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.example.project.util.FileUploadResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author 岩
 * @Package org.example.project.service.impl
 * @Project MyApp
 * @Name FileServiceImpl
 * @Date 2024-05-02 17:24
 * @Filename FileServiceImpl
 */

@Slf4j
@Service
public class FileServiceImpl {

    /**
     * 拦截的url，虚拟路径
     * */
    public String pathPattern = "files";

    /**
     * 文件保存路径
     */
    private static final String FILE_DIR = "/src/main/webapp/img";

    public String filePath = System.getProperty("user.dir") + File.separator + FILE_DIR + File.separator;

    private static final AtomicInteger SUFFIX = new AtomicInteger(0);

    @Value(value = "${file.upload.suffix:jpg,jpeg,png,bmp,xls,xlsx,pdf}")
    private String fileUploadSuffix;

    public FileUploadResponse upload(MultipartFile file) {
        FileUploadResponse result = new FileUploadResponse();
        if (file.isEmpty()) {
            log.error("the file to be uploaded is empty");
            return result;
        }
        List<String> suffixList = Lists.newArrayList(fileUploadSuffix.split(","));

        try {
            //校验文件后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename != null ?
                    originalFilename.substring(originalFilename.lastIndexOf(".") + 1) : null;
            if (!suffixList.contains(suffix)) {
                log.error("unsupported file format");
                return result;
            }
            // 保存文件
            String fileName = timeFormat(System.currentTimeMillis()) + SUFFIX.getAndIncrement() + "." + suffix;
            String absolutePath = filePath + fileName;
            log.info("absolutePath is {}", absolutePath);
            file.transferTo(new File(absolutePath));

            String separator = "/";
            String path = separator + pathPattern + separator + fileName;

            result.setPath(path);
            result.setFileName(fileName);

        } catch (Exception e) {
            log.error("the file upload error occurred. e ", e);
        }
        return result;
    }

    public static String timeFormat(Long time) {
        if (Objects.isNull(time)) {
            return null;
        }
        DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(time);
    }

}
